﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PUCIT.eFCS.Business;
using System.Collections;
using System.Collections.Specialized;
using PUCIT.eFCS.Utility.Encryption;
using System.Web.Configuration;
using System.Web.UI.HtmlControls;
using System.ComponentModel;
using System.Xml;

namespace PUCIT.eFCS
{
    public partial class DesignStationSections : System.Web.UI.Page
    {

        private Button GetButton(string id, string name)
        {
            Button b = new Button();
            b.Text = name;
            b.ID = id;
            b.Click += new EventHandler(putToDB);
            //b.OnClientClick = "ButtonClick('" + b.ClientID + "')";
            return b;
        }
        protected void putToDB(object sender, EventArgs e)
        {
            char ch = ((Button)sender).ID.ElementAt(((Button)sender).ID.Length - 1);
            String var = "htmlDivControl" + ch;
            

            HtmlGenericControl htmlDivControlTemp = (HtmlGenericControl)Sections.FindControl(var);

            BusinessClass eFCS = new BusinessClass();
            List<Section> sections = new List<Section>();
            int documentId = -1;

            
            float version = (float)Session["version"];
            string documentName = (string)Session["DocumentName"];
            string documentVersion = version.ToString() + ".0";
            List<int> sectionIds = (List<int>)Session["sectionIds"];

            //remove corresponding row from field


            Section stationSection = new Section();
            if ((Boolean)Session["isNew"])
            {
                if (Convert.ToInt32(ch.ToString()) == 1)
                {
                    //version = (float)Session["version"] + 1;
                    version = (float)Session["version"];
                    documentVersion = version.ToString() + ".0";
                    documentId = eFCS.InsertNewDocument(documentName, documentVersion, false, Convert.ToInt32((string)Session["TotalSections"]));
                    
                }
                else
                {


                    documentId = eFCS.GetDocumentId(documentName, documentVersion);
                    sections = (List<Section>)Session["sections"];
                    eFCS.updateDocumentCompletedSection(documentId, Convert.ToInt32(ch.ToString()));
                }



                String secTitle = (Sections.FindControl("txt" + ch) as TextBox).Text;

                stationSection.SectionTitle = secTitle;
                stationSection.SeqNo = Int32.Parse(ch.ToString());

                String sectionUser = (Sections.FindControl("DDL" + ch) as DropDownList).SelectedValue;
                int userId = eFCS.GetUserIdByUserName(sectionUser);

                stationSection.UserId = userId;

                int sectionId = eFCS.InsertSectionWithDocumentId(documentId, stationSection.SeqNo, secTitle);
                stationSection.SectionId = sectionId;

                eFCS.InsertSectionUserRow(sectionId, stationSection.UserId, "To");
            }
            
            XmlDocument xdoc = new XmlDocument();
            string abc = "<formdata>";
            abc += htmlDivControlTemp.InnerText;
            abc += "</formdata>";
            int index = abc.IndexOf('&');
            while (index != -1)
            {
                index=abc.IndexOf('&');
                abc=abc.Remove(index, index + 4);
                index = abc.IndexOf('&');
            }
            xdoc.LoadXml(abc);
            xdoc.Save(Server.MapPath("~\\sectionXML.xml"));
            stationSection.SectionFields = parser(Server.MapPath("~\\sectionXML.xml"));

            if (!(Boolean)Session["isNew"])
            {
                List<int> prevFieldIds = eFCS.GetFieldIdList(sectionIds[Convert.ToInt32(ch.ToString()) - 1]);
                eFCS.delSpecificFields(prevFieldIds);
            }

            foreach (Field field in stationSection.SectionFields)
            {
                int fieldseqNo = field.SeqNo;
                string fieldlabel = field.FieldLabel;
                string htmlFieldId = field.FieldHtmlId;
                string html = field.FieldHtml;
                eFCS.InsertFieldBySectionId(sectionIds[Convert.ToInt32(ch.ToString())-1], fieldseqNo, fieldlabel, "stdName", html);
                
            }

            //is say aagay inshalah phir kabhi chalain ge.
            if ((Boolean)Session["isNew"])
            {
                sections.Add(stationSection);
            }

            string s = (string)Session["TotalSections"];
            int noOfSections = Convert.ToInt32(s);
            int nextSectionId;
            if (Int32.Parse(ch.ToString()) == noOfSections)
            {
                eFCS.UpdateDocument(documentId, true);
                
                for (int i = 0; i < sections.Count; i++)
                {
                    if (i + 1 < sections.Count)
                    {
                        nextSectionId = sections[i + 1].SectionId;
                    }
                    else
                    {
                        nextSectionId = sections[0].SectionId;
                    }

                    eFCS.InsertNewAction(sections[i].SectionId, "Submit", "//", nextSectionId);
                }
            }
                
            // DB me sab section save honay chaiyain.

            
            Session["sections"] = sections;
            

        }
        private List<Field> parser(String fileName)
        { 
           //string FormName = "General Request Form";
           int seqno = 1;
           string htmltag;
           string label;
           string htmlfieldid;
           htmlfieldid = "";
           //List<Section> sections = new List<Section>();
           //Section Student = new Section();
           List<Field> fields = new List<Field>();
           
            // Read a document
            XmlTextReader textReader = new XmlTextReader(fileName);
                
            // Read until end of file
            while (textReader.Read())
            {
                XmlNodeType nType = textReader.NodeType;
                if (nType == XmlNodeType.EndElement)
                {
                }
                
                // if node type is an element
                else if (nType == XmlNodeType.Element)
                {
                    if (textReader.Name.ToString() == "p")
                    {
                        htmltag = "<br/>";
                        do
                        {
                            textReader.Read();
                            nType = textReader.NodeType;

                        } while (nType == XmlNodeType.Whitespace);
                        label = textReader.Value;

                        do
                        {
                            textReader.Read();
                            nType = textReader.NodeType;
                        }while (nType != XmlNodeType.Element);
        
                        if (nType == XmlNodeType.Element)
                        {
                            if (textReader.Name.ToString() == "input")
                            {
                                htmltag += " <input ";
                                htmlfieldid = seqno + "-" + label;
                                if (textReader.HasAttributes) 
                                {
                                    while (textReader.MoveToNextAttribute())
                                    {
                                        htmltag += textReader.Name + "=" + textReader.Value + " ";
                                        /*if (textReader.Name.ToString() == "type" && textReader.Value.ToString() == "checkbox")
                                        {
                                            //prefix+"Label's String"+"RB";
                                            htmlfieldid = "";
                                        }*/
                                        
                                        if (textReader.Name.ToString() == "type" && textReader.Value.ToString() == "radio")
                                        {
                                            htmlfieldid = seqno + "-"+ label + "-RB" ;
                                        }
                                    }
                                   // htmltag += " />";
                                }
                                else if (textReader.Name.ToString() == "textarea")
                                {
                                    htmltag += " <textarea ";
                                    htmlfieldid = seqno + "-" + label;
                                    if (textReader.HasAttributes)
                                    {
                                        while (textReader.MoveToNextAttribute())
                                        {

                                            htmltag += textReader.Name + "=" + textReader.Value + " ";
                                        }
                                    }
                                    //htmltag += ">";
                                    textReader.Read();
                                    //htmltag += " </textarea>";
                                }
                                else if (textReader.Name.ToString() == "select")
                                {

                                    htmltag += " <select ";
                                    htmlfieldid = seqno + "-" + label + "-DDL";
                                    
                                    if (textReader.HasAttributes)
                                    {
                                        while (textReader.MoveToNextAttribute())
                                        {
                                            htmltag += textReader.Name + "=" + textReader.Value + " ";
                                        }
                                    }
                                    htmltag += ">";

                                    do
                                    {
                                        textReader.Read();
                                        nType = textReader.NodeType;
                                    } while (nType != XmlNodeType.Element);

                                    while (textReader.Name.ToString() == "option")
                                    {
                                        htmltag += "<option ";
                                        if (textReader.HasAttributes)
                                        {
                                            while (textReader.MoveToNextAttribute())
                                            {;
                                                htmltag += textReader.Name + "=" + textReader.Value + " ";
                                            }
                                        }
                                        htmltag += ">";
                                        textReader.Read();

                                        htmltag += textReader.Value +"</option>";
                                        string selectagfinder;
                                        do
                                        {
                                            textReader.Read();
                                            nType = textReader.NodeType;
                                            selectagfinder = textReader.Name.ToString();
                                        } while (nType != XmlNodeType.Element && selectagfinder != "select");
                                    }
                                    //textReader.MoveToElement();
                                    htmltag += "</select>";
                                    htmlfieldid = "DDL";
                                } 
                            }



                            Field field = new Field();
                            field.FieldLabel = label;
                            field.SeqNo = seqno;
                            field.FieldHtml = htmltag;
                            //field.FieldHtml+=htmlfieldid; this step is necessary
                            field.FieldHtmlId = seqno + "-" + label + "-File"; ;
                            fields.Add(field);
                           
                            seqno++;
                            
                        }

                    }

                    // if node type is white space
                    else if (nType == XmlNodeType.Whitespace)
                    {
                        Console.WriteLine("WhiteSpace:" + textReader.Name.ToString());

                    }
                }
                //Console.ReadKey();
            }

            /*field = new Field();
            field.FieldLabel = "Add Attachment:";
            field.FieldHtmlId = "";
            field.FieldHtml = "<input type='file' name='datasize' size='30' ";
            section.SectionFields.Add(field);*/

            Field Attachmentfield = new Field();
            Attachmentfield.FieldLabel = "Attachment: ";
            Attachmentfield.SeqNo = seqno;
            Attachmentfield.FieldHtml = "<input type='file' name='datasize' id='datasize' size='30' ";
            //field.FieldHtml+=htmlfieldid; this step is necessary
            Attachmentfield.FieldHtmlId = seqno + "-Attachment-File";
            fields.Add(Attachmentfield);

            seqno++;

            return fields;// fieldsToPopulate = fields;
    
        }
        protected void showCkEditor(object sender, EventArgs e)
        {
            CKEditor1.Visible = true;
            
            char ch=((Button)sender).ID.ElementAt(((Button)sender).ID.Length-1);
            String var = "htmlDivControl" + ch;

            HtmlGenericControl htmlDivControlTemp = (HtmlGenericControl )Sections.FindControl(var);
            
            
            htmlDivControlTemp.InnerHtml = "";
            htmlDivControlTemp.Visible = false;
            /*
            htmlDivControl.InnerHtml = "";
            htmlDivControl.Visible = false;
            */ 
        }
        protected void hideCkEditorShowHtml(object sender, EventArgs e)
        {
            CKEditor1.Visible = false;

            char ch = ((Button)sender).ID.ElementAt(((Button)sender).ID.Length-1);

            HtmlGenericControl htmlDivControlTemp = (HtmlGenericControl)Sections.FindControl("htmlDivControl" + ch);
            
            htmlDivControlTemp.Visible = true;
            htmlDivControlTemp.InnerHtml = CKEditor1.Text; ;
            
            
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            int documentId = 0;
            BusinessClass eFCS = new BusinessClass();

            if (!Page.IsPostBack)
            {
                


                Session["isNew"] = true;
                

                string encryptedQueryStringPrameters = (string)HttpContext.Current.Session["params"];

                HttpContext.Current.Session.Remove("params");

                // Decrypt query strings parameters
                string cryptoKey = WebConfigurationManager.AppSettings["CryptoKey"];
                string decryptedQueryString = CryptoQueryStringHandler.DecryptQueryStrings(encryptedQueryStringPrameters, cryptoKey);

                string[] keyValuePair = decryptedQueryString.Split('='); // e.g. {documentId,15

                documentId = int.Parse(keyValuePair[1]);
                Session["documentId"] = documentId;


                if (documentId != null)
                {
                    Session["isNew"] = false;
                    Session["version"]=eFCS.GetDocumentVersionByDocumentId(documentId);
                    Session["totalSections"] = eFCS.GetDocumentTotalSectionsByDocumentId(documentId);
                    Session["completedSections"] = eFCS.GetDocumentCompletedSectionsByDocumentId(documentId);
                    Session["DocumentName"] = eFCS.GetDocumentNameByDocumentId(documentId);
                }

                Session["updatedDocId"]=eFCS.InsertNewDocument(Session["DocumentName"].ToString() + "copy", Session["version"].ToString(), false,Convert.ToInt32(Session["totalSections"]), Convert.ToInt32(Session["completedSections"]));

            }
            documentId = (int )Session["documentId"];
            int noOfSections = Int32.Parse(Session["totalSections"].ToString());
            int completedSections = Int32.Parse(Session["completedSections"].ToString());

            LblFormName.Text = (string)Session["DocumentName"];

            BusinessClass obj = new BusinessClass();
            List<string> AllcategoryNames = obj.GetAllCategoriesNames();

            CKEditor1.Visible = false;

            //int j=completedSections+1;
            //int t=completedSections+1;

            int j = 1;
            int t = 1;
            

            

            Document document = eFCS.GenerateFormTemplate(documentId);
            //seqNo is missing.

            List<int> sectionIds=new List<int>();


            foreach (Section section in document.DocumentSections)  //i=completedSection before.
            {
                   //add row to section table
                    if (documentId == null)
                    {
                        Sections.Controls.Add(new LiteralControl("<h3>Section " + j + ":</h3>"));
                        Sections.Controls.Add(new LiteralControl("<br/>"));

                        Label lbl = new Label();
                        lbl.Text = "Section Name: ";
                        TextBox txt = new TextBox();
                        txt.ID = "txt" + t.ToString();

                        Sections.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp"));

                        DropDownList DDL = new DropDownList();
                        DDL.ID = "DDL" + t.ToString();
                        foreach (string name in AllcategoryNames)
                        {
                            DDL.Items.Add(new ListItem(name));
                        }

                        Sections.Controls.Add(lbl);
                        Sections.Controls.Add(txt);
                        Sections.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"));
                        Sections.Controls.Add(DDL);
                    }


                    Button editBtn = new Button();
                    editBtn.Text = "Edit Design";
                    editBtn.ID = "editBtn" + j;

                    editBtn.Click += new EventHandler(this.showCkEditor);

                    Button endEditing = new Button();
                    endEditing.Text = "End Editing";
                    endEditing.ID = "endEditing" + j;

                    endEditing.Click += new EventHandler(this.hideCkEditorShowHtml);

                    HtmlGenericControl htmlDivControl = new HtmlGenericControl("div");
                    htmlDivControl.ID = "htmlDivControl" + j;


                    if (documentId != null)
                    {
                        HtmlGenericControl htmlDivControlSecName = new HtmlGenericControl("div");
                        htmlDivControlSecName.ID = "htmlDivControlSecName" + j;
                        htmlDivControlSecName.InnerHtml = ("<h3><u>" + section.SectionTitle + "</u></h3>");
                        Sections.Controls.Add(htmlDivControlSecName);
                        string secHtml = "";

                        int updatedSecId = -1;
                        if (!Page.IsPostBack)
                        {
                            updatedSecId = eFCS.InsertSectionWithDocumentId((int)Session["updatedDocId"], section.SeqNo, section.SectionTitle);
                            eFCS.InsertSectionUserRow(updatedSecId, section.UserId, "To");
                            sectionIds.Add(updatedSecId);
                        }
                        
                        

                        foreach (Field field in section.SectionFields)
                        {
                            if (!Page.IsPostBack)
                            {
                                eFCS.InsertFieldBySectionId(updatedSecId, field.SeqNo, field.FieldLabel, field.FieldHtmlId, field.FieldHtml);
                            }
                            //add same row to field table
                            if (field.FieldHtml.IndexOf("type='file'") > 0)
                            {
                                secHtml += (field.FieldLabel + "<a>" + field.FieldHtml + "</a>");
                            }
                            else
                            {
                                secHtml += (field.FieldLabel + field.FieldHtml);
                            }

                            secHtml += "<br><br>";
                        }


                        htmlDivControl.InnerHtml = secHtml;
                    }

                    endEditing.Click += new EventHandler(putToDB);
                    Sections.Controls.Add(htmlDivControl);
                    Sections.Controls.Add(editBtn);
                    Sections.Controls.Add(endEditing);

                    j++;
                    t++;

                }

            if (!Page.IsPostBack)
            {
                int nextSectionId;
                for (int i = 0; i < sectionIds.Count; i++)
                {
                    if (i + 1 < sectionIds.Count)
                    {
                        nextSectionId = sectionIds[i + 1];
                    }
                    else
                    {
                        nextSectionId = sectionIds[0];
                    }

                    eFCS.InsertNewAction(sectionIds[i], "Submit", "//", nextSectionId);
                }
            }

            Session["sectionIds"] = sectionIds;
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            
            //return false;
            ArrayList keys = new ArrayList(Button1.Attributes.Keys);
            BusinessClass eFCS = new BusinessClass();
            
            //float version = (float)Session["version"] + 1;
            float version = (float)Session["version"];
            string documentName = (string)Session["DocumentName"];  
            string documentVersion = version.ToString() + ".0";


            int documentId = eFCS.GetDocumentId(documentName, documentVersion);



            NameValueCollection queryStringParameters = new NameValueCollection();
            queryStringParameters.Add("documentId", documentId.ToString());

            // Encrypt query string parameters
            string encryptedString = CryptoQueryStringHandler.EncryptQueryStrings(queryStringParameters, WebConfigurationManager.AppSettings["CryptoKey"]);

            if (Session["params"] != null)
                Session.Remove("params");

            Session.Remove("page");

            Response.Redirect("GenerateNewTemplate.aspx?" + encryptedString);

        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            if ((Boolean )Session["isNew"])
            {
                Response.Redirect("DesignNewTemplate.aspx");
            }
            else
            {
                Response.Redirect("ViewTemplateList.aspx");
            }
        }
    }
}
